#! _*_ coding: utf8 _*_
from django.contrib.auth import get_user_model
from rest_framework import serializers

from common.serializers import VideoSeri, ExcludeableSeri
from school.models import School
from .models import *


class SimpleSchoolSeri(serializers.ModelSerializer):
    class Meta:
        model = School
        fields = ('pk', 'name')


class UserProfileSeri(serializers.ModelSerializer):

    def create(self, validated_data):
        return UserProfile(**validated_data)

    def update(self, instance, validated_data):
        instance.age = validated_data.get('age', instance.age)
        instance.phone = validated_data.get('phone', instance.phone)
        instance.desc = validated_data.get('desc', instance.desc)
        instance.save()
        return instance

    class Meta:
        model = UserProfile
        fields = ('age', 'phone', 'desc', 'icon')


class UserSeri(ExcludeableSeri):
    userprofile = UserProfileSeri(required=False)
    schools = serializers.SerializerMethodField('user_schools')
    teacher = serializers.SerializerMethodField('user_teacher')
    student = serializers.SerializerMethodField('user_student')
    videos = serializers.SerializerMethodField('user_videos')

    def create(self, validated_data):
        json_up = validated_data.pop('userprofile')

        username = self.initial_data.get('username', None)
        if username:
            try:
                user = User.objects.get(username=username)
            except Exception as e:
                user = User.objects.create(**validated_data)
        else:
            user = User.objects.create(**validated_data)
        UserProfile(user=user, **json_up)
        return user

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('userprofile', {})

        if hasattr(instance, 'userprofile'):
            profile = instance.userprofile
            seri = UserProfileSeri(profile, data=profile_data)

            if seri.is_valid():
                seri.save()
        else:
            seri = UserProfileSeri(data=profile_data)
            if seri.is_valid():
                profile = seri.save()
                profile.user = instance
                profile.save()

        instance.first_name = validated_data.get('first_name', instance.first_name)
        instance.last_name = validated_data.get('last_name', instance.last_name)
        instance.save()
        return instance

    def user_schools(self, user):
        if not hasattr(user, 'owner_schools'):
            return []
        else:
            return SimpleSchoolSeri(user.owner_schools, many=True).data

    def user_teacher(self, user):
        if not hasattr(user, 'teacher'):
            return {}
        else:
            t = user.teacher
            return {'pk': t.pk,
                    'schools': SimpleSchoolSeri(t.teacher_schools.all(), many=True).data}

    def user_student(self, user):
        if not hasattr(user, 'student'):
            return {}
        else:
            s = user.student
            return {'pk': s.pk,
                    'schools': SimpleSchoolSeri(s.student_schools.all(), many=True).data,
                    'classes_num': str(len(s.classes.all()))}

    def user_videos(self, user):
        if not hasattr(user, 'user_videos'):
            return []
        else:
            videos = user.user_videos.all()
            return VideoSeri(videos, many=True).data

    class Meta:
        model = get_user_model()
        fields = ('pk', 'username', 'first_name', 'last_name', 'userprofile', 'schools', 'teacher', 'student', 'videos')
        extra_kwargs = {
            'username': {
                'validators': []
            }
        }
